package org.github.manx98.jlibhac.fssystem;

import org.github.manx98.jlibhac.fs.fsa.DirectoryEntry;
import org.github.manx98.jlibhac.fs.fsa.DirectoryEntryType;
import org.github.manx98.jlibhac.fs.fsa.IDirectory;
import org.github.manx98.jlibhac.fs.fsa.OpenDirectoryMode;

import java.io.IOException;

/**
 * @author Manx98
 * @version 1.0
 * @since 2022/10/3 14:49
 */
public class PartitionDirectory extends IDirectory {
    private final PartitionFileSystem parentFileSystem;
    private final String path;
    private final OpenDirectoryMode mode;
    private int currentIndex;

    public PartitionDirectory(PartitionFileSystem partitionFileSystem, String path, OpenDirectoryMode mode) {
        this.parentFileSystem = partitionFileSystem;
        if ("/".equals(path)) throw new IllegalArgumentException("Path must not be /");
        this.path = path;
        this.mode = mode;
        this.currentIndex = 0;
    }

    @Override
    public long doRead(DirectoryEntry[] entryBuffer) throws IOException {
        if (!mode.hasFlag(OpenDirectoryMode.File)) {
            return 0;
        }
        int entriesRemaining = parentFileSystem.Files.length - currentIndex;
        int toRead = Math.min(entriesRemaining, entryBuffer.length);
        for (int i = 0; i < toRead; i++) {
            PartitionFileEntry fileEntry = parentFileSystem.Files[currentIndex];
            DirectoryEntry entry = new DirectoryEntry();
            entryBuffer[i] = entry;
            entry.Name = fileEntry.name;
            entry.Type = DirectoryEntryType.File;
            entry.Size = fileEntry.size;
            currentIndex++;
        }
        return toRead;
    }

    @Override
    public long doGetEntryCount() {
        int count = 0;

        if (mode.hasFlag(OpenDirectoryMode.File)) {
            count += parentFileSystem.Files.length;
        }
        return count;
    }
}
